/* eslint-disable react/react-in-jsx-scope */
import useCountDown from '@/hooks/useCountDown'
import { getCode, login } from '@/store/actions/login'
import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { AxiosError } from 'axios'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
type LoginForm={
  mobile:string,
  code:string
}

const Login = () => {
  // const location = useLocation<{from:string} | undefined>()

  const { count, start } = useCountDown(5, () => { setSendable(true) })
  // eslint-disable-next-line no-unused-vars
  const [sendable, setSendable] = useState(true)
  const history = useHistory<{from:string} | undefined>()
  console.log(history.location)
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const inputRef = useRef<InputRef>(null)
  // 用户登录
  const onFinish = async (values:LoginForm) => {
    console.log(values)
    try {
      await dispatch(login(values))
      // 登录成功提示
      Toast.show({
        icon: 'success',
        content: '登录成功'
      })
      const path = history.location.state?.from || '/'
      console.log(path, 1234)

      history.replace(path)
      // history.replace('/')
    } catch (e) {
      // console.dir(e.response.data.message)
      // alert(e.respone.data.message)
      const error = e as AxiosError<{message:string}>
      const content = error.response?.data.message || '登录失败'
      Toast.show({
        content,
        icon: 'fail'
      })
    }
  }
  const onSendCode = async () => {
    // 拿到手机号
    const mobile = form.getFieldValue('mobile')
    // 校验
    const hasError = form.getFieldError('mobile')
    // 没有写手机号 或者 手机号格式不对
    if (!mobile || hasError.length > 0) {
      inputRef.current?.focus()
    }
    // 手机号不为空，且通过校验，可以请求接口发送验证码
    // alert('ok')
    try {
      // if (!sendable) {
      //   return
      // }
      setSendable(false)
      // 请求开始倒计时
      start()
      await dispatch(getCode(mobile))
      // 登录成功提示
      Toast.show({ icon: 'success', content: '短信已发送' })
    } catch (e) {
      const error = e as AxiosError<{message:string}>
      const content = error.response?.data.message || '登录失败'
      Toast.show({ icon: 'fail', content })
    }
  }

  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item className="login-item"
          name='mobile'
          rules={
            [
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]
          }
          >
            <Input placeholder="请输入手机号" ref={inputRef} />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span onClick={sendable ? onSendCode : () => {}} className="code-extra">{sendable ? '发送验证码' : count + '之后重新获取'}</span>}
          >
            <Form.Item name="code" className="login-item"
             rules={[{ required: true, message: '请输入验证码' }]}
            >
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
